/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { ChildPlaneCommandProps } from './types';
import { isEmpty } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { ctx2 } from '@app-base/module';

type FormDataType = {
  point1: pickedVertexData;
  point2: pickedVertexData;
  normal: pickedFaceData;
  type: number;
  radius: number;
};

export function TwoPointRadius({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) {
  const { picker } = useTools();

  const initData: FormDataType = {
    point1: undefined,
    point2: undefined,
    normal: undefined,
    radius: 100,
    type: 0,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);
  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props === null) {
      setFormData(initData);
      return;
    }
    if (props) {
      const point1 = props?.params?.point1;
      const point2 = props?.params?.point2;
      const normal = props?.params?.normal;
      await initEditDependency([point1, point2]);
      const defaultType =
        props?.params?.mode === 'circle-2point-radius'
          ? 0
          : props?.params?.reverse
            ? 2
            : 1;
      const defaultPoint1 = point1
        ? (picker.generatePickObjByPickID(point1) as pickedVertexData)
        : undefined;
      const defaultPoint2 = point2
        ? (picker.generatePickObjByPickID(point2) as pickedVertexData)
        : undefined;
      const defaultPlane = picker.generatePickObjByPickID(
        normal,
      ) as pickedFaceData;
      const radius = props?.params?.radius;
      setFormData({
        point1: defaultPoint1,
        point2: defaultPoint2,
        normal: defaultPlane,
        radius: radius,
        type: defaultType,
      });

      setSolution(props?.params?.solution);
    }
  }, [editDxid]);

  const checkAndFinishDraw = async () => {
    const { point1, point2, radius } = formData;
    if (isEmpty(point1) || isEmpty(point2) || radius === null || radius === 0)
      return;

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-arc-bitangent-radius', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const { point1, point2, normal, radius } = formData;
    return point1 != null && point2 != null && normal != null && radius != null;
  };

  const execute = async (preview: boolean = true) => {
    const { point1, point2, normal, radius, type } = formData;
    const planeId = normal?.meshId;

    return confirmCommand(
      {
        type: 'ArcOfCircle',
        a: {
          mode: type === 0 ? 'circle-2point-radius' : '2point-radius',
          point1: point1?.vertexId,
          point2: point2?.vertexId,
          radius: radius,
          solution: solution,
          normal: planeId,
          reverse: type === 2,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    const { point1, point2, radius } = formData;
    if (isEmpty(point1) || isEmpty(point2) || radius === null || radius === 0) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);

    ctx2.viewer.requestRender();
  };

  useAsyncEffect(preview, [solution]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      point1: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      point2: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      radius: {
        type: 'number',
        title: '半径',
        format: NumberInputFormat.Length,
      },
      type: {
        title: '圆限制',
        type: 'number',
        oneOf: [
          {
            type: 'number',
            title: '整圆',
            const: 0,
          },
          {
            type: 'number',
            title: '顺时针',
            const: 1,
          },
          {
            type: 'number',
            title: '逆时针',
            const: 2,
          },
        ],
        default: 0,
      },
      normal: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      solution: MULTI_SOLUTION_SCHEMA,
    },
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      submitLoading={isLoading}
      onCancel={onClose}
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        const data = {
          point1: v.point1,
          point2: v.point2,
          normal: v.normal,
          radius: v.radius,
          type: v.type,
        };
        setFormData(data);
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        point1: {
          'ui:placeholder': '请输入点1',
          'ui:autofocus': true,
        },
        point2: {
          'ui:placeholder': '请输入点2',
        },
        radius: {
          'ui:placeholder': '请输入半径',
        },
        normal: {
          'ui:placeholder': '请输入支持面',
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
